Imports System.Web.Services.Description
Imports System.Web.Services
Imports System.Xml.Serialization
Imports System.Collections.Specialized
Imports System.Runtime.InteropServices
Imports System.Runtime.CompilerServices
Imports System
Imports System.Xml
Imports System.Xml.Schema
Imports Microsoft.Win32
Imports System.IO.Path
Imports System.Reflection
Imports System.Web.Services.Discovery
Imports System.IO
Imports System.CodeDom.Compiler
Imports System.CodeDom
Imports System.Net
Imports System.ComponentModel
Imports System.Drawing



Friend Class Wsdl



    ' Methods
    Private Sub AddDocument(ByVal path As String, ByVal document As Object, ByVal schemas As XmlSchemas, ByVal descriptions As ServiceDescriptionCollection)
        Dim serviceDescription As ServiceDescription = TryCast(document, ServiceDescription)
        If (Not serviceDescription Is Nothing) Then
            If (descriptions.Item(serviceDescription.TargetNamespace) Is Nothing) Then
                descriptions.Add(serviceDescription)
                Dim w As New StringWriter
                Dim writer As New XmlTextWriter(w)
                writer.Formatting = Formatting.Indented
                serviceDescription.Write(writer)
                Me.Wsdls.Add(w.ToString)
            Else
                Me.CheckPoint(MessageType.Warning, String.Format(Wsdl.duplicateService, serviceDescription.TargetNamespace, path))
            End If
        Else
            Dim schema As XmlSchema = TryCast(document, XmlSchema)
            If (Not schema Is Nothing) Then
                If (schemas.Item(schema.TargetNamespace) Is Nothing) Then
                    schemas.Add(schema)
                    Dim writer3 As New StringWriter
                    Dim writer4 As New XmlTextWriter(writer3)
                    writer4.Formatting = Formatting.Indented
                    schema.Write(writer4)
                    Me.Xsds.Add(writer3.ToString)
                Else
                    Me.CheckPoint(MessageType.Warning, String.Format(Wsdl.duplicateSchema, serviceDescription.TargetNamespace, path))
                End If
            End If
        End If
    End Sub

    Private Shared Sub AddElementAndType(ByVal schema As XmlSchema, ByVal baseXsdType As String, ByVal ns As String)
        Dim item As New XmlSchemaElement
        item.Name = baseXsdType
        item.SchemaTypeName = New XmlQualifiedName(baseXsdType, ns)
        schema.Items.Add(item)
        Dim type As New XmlSchemaComplexType
        type.Name = baseXsdType
        Dim content As New XmlSchemaSimpleContent
        type.ContentModel = content
        Dim extension As New XmlSchemaSimpleContentExtension
        extension.BaseTypeName = New XmlQualifiedName(baseXsdType, "http://www.w3.org/2001/XMLSchema")
        content.Content = extension
        schema.Items.Add(type)
    End Sub

    Private Shared Sub AddFakeSchemas(ByVal parent As XmlSchema, ByVal schemas As XmlSchemas)
        If (schemas.Item("http://www.w3.org/2001/XMLSchema") Is Nothing) Then
            Dim item As New XmlSchemaImport
            item.Namespace = "http://www.w3.org/2001/XMLSchema"
            item.Schema = Wsdl.CreateFakeXsdSchema("http://www.w3.org/2001/XMLSchema", "schema")
            parent.Includes.Add(item)
        End If
        If (schemas.Item("http://schemas.xmlsoap.org/soap/encoding/") Is Nothing) Then
            Dim import2 As New XmlSchemaImport
            import2.Namespace = "http://schemas.xmlsoap.org/soap/encoding/"
            import2.Schema = Wsdl.CreateFakeSoapEncodingSchema("http://schemas.xmlsoap.org/soap/encoding/", "Array")
            parent.Includes.Add(import2)
        End If
        If (schemas.Item("http://schemas.xmlsoap.org/wsdl/") Is Nothing) Then
            Dim import3 As New XmlSchemaImport
            import3.Namespace = "http://schemas.xmlsoap.org/wsdl/"
            import3.Schema = Wsdl.CreateFakeWsdlSchema("http://schemas.xmlsoap.org/wsdl/")
            parent.Includes.Add(import3)
        End If
    End Sub

    Private Shared Sub AddSimpleType(ByVal schema As XmlSchema, ByVal typeName As String, ByVal baseXsdType As String)
        Dim item As New XmlSchemaSimpleType
        item.Name = typeName
        Dim restriction As New XmlSchemaSimpleTypeRestriction
        restriction.BaseTypeName = New XmlQualifiedName(baseXsdType, "http://www.w3.org/2001/XMLSchema")
        item.Content = restriction
        schema.Items.Add(item)
    End Sub

    Public Sub Cancel()
        Me.cancelled = True
    End Sub

    Private Sub ChangeBaseType(ByVal compileUnit As CodeCompileUnit)
        If ((Not Me.WsdlProperties.ProxyBaseType Is Nothing) AndAlso (Me.WsdlProperties.ProxyBaseType.Length <> 0)) Then
            Dim type As Type = type.GetType(Me.WsdlProperties.ProxyBaseType, True)
            Dim namespace2 As CodeNamespace
            For Each namespace2 In compileUnit.Namespaces
                Dim declaration As CodeTypeDeclaration
                For Each declaration In namespace2.Types
                    Dim flag As Boolean = False
                    Dim declaration2 As CodeAttributeDeclaration
                    For Each declaration2 In declaration.CustomAttributes
                        If (declaration2.Name = GetType(WebServiceBindingAttribute).FullName) Then
                            flag = True
                            Exit For
                        End If
                    Next
                    If flag Then
                        declaration.BaseTypes.Item(0) = New CodeTypeReference(type.FullName)
                    End If
                Next
            Next
        End If
    End Sub

    Private Sub CheckPoint(ByVal status As MessageType, ByVal message As String, Optional ByRef txtBox As Web.UI.WebControls.TextBox = Nothing)
        If Not Me.cancelled Then
            'MainForm.ShowMessage(Me, status, message)

            If Not txtBox Is Nothing Then
                strMessage = strMessage + message + vbNewLine
            End If
        End If
    End Sub

    Private Shared Sub CollectIncludes(ByVal schema As XmlSchema, ByVal includeSchemas As Hashtable)
        Dim external As XmlSchemaExternal
        For Each external In schema.Includes
            Dim schemaLocation As String = external.SchemaLocation
            If TypeOf external Is XmlSchemaImport Then
                external.SchemaLocation = Nothing
            ElseIf ((TypeOf external Is XmlSchemaInclude AndAlso (Not schemaLocation Is Nothing)) AndAlso (schemaLocation.Length > 0)) Then
                Dim str2 As String = Path.GetFullPath(schemaLocation).ToLower
                If (includeSchemas.Item(str2) Is Nothing) Then
                    Dim schema2 As XmlSchema = Wsdl.ReadSchema(schemaLocation)
                    includeSchemas.Item(str2) = schema2
                    Wsdl.CollectIncludes(schema2, includeSchemas)
                End If
                external.Schema = DirectCast(includeSchemas.Item(str2), XmlSchema)
                external.SchemaLocation = Nothing
            End If
        Next
    End Sub

    Private Sub Compile(ByVal userSchemas As XmlSchemas)
        Dim parent As New XmlSchema
        Dim schema2 As XmlSchema
        For Each schema2 In userSchemas
            If ((Not schema2.TargetNamespace Is Nothing) AndAlso (schema2.TargetNamespace.Length = 0)) Then
                schema2.TargetNamespace = Nothing
            End If
            If (schema2.TargetNamespace = parent.TargetNamespace) Then
                Dim include As New XmlSchemaInclude
                include.Schema = schema2
                parent.Includes.Add(include)
                Continue For
            End If
            Dim item As New XmlSchemaImport
            item.Namespace = schema2.TargetNamespace
            item.Schema = schema2
            parent.Includes.Add(item)
        Next
        Wsdl.AddFakeSchemas(parent, userSchemas)
        Try
            Dim schemas As New XmlSchemaSet
            AddHandler schemas.ValidationEventHandler, New ValidationEventHandler(AddressOf Me.ValidationCallbackWithErrorCode)
            schemas.Add(parent)
            If (schemas.Count = 0) Then
                Me.CheckPoint(MessageType.Warning, Wsdl.schemaValidationFailure)
            End If
        Catch exception As Exception
            Me.CheckPoint(MessageType.Warning, (Wsdl.schemaValidationFailure & ChrW(10) & exception.Message))
        End Try
    End Sub

    Private Sub CreateCodeGenerator(<Out()> ByRef codeGen As ICodeGenerator, <Out()> ByRef fileExtension As String)
        Dim language As Language = Me.WsdlProperties.Language
        Select Case language
            Case language.CS
                Me.codeProvider = New Microsoft.CSharp.CSharpCodeProvider
                Exit Select
            Case language.VB
                Me.codeProvider = New VBCodeProvider
                Exit Select
            Case Else
                If (language <> language.Custom) Then
                    Throw New Exception("Unknown language")
                End If
                Dim type As Type = type.GetType(Me.WsdlProperties.CustomCodeDomProvider)
                If (type Is Nothing) Then
                    Throw New TypeLoadException(("Type '" & Me.WsdlProperties.CustomCodeDomProvider & "' is not found"))
                End If
                Me.codeProvider = DirectCast(Activator.CreateInstance(type), CodeDomProvider)
                Exit Select
        End Select
        If (Not Me.codeProvider Is Nothing) Then
            'codeGen = codeProvider.CreateGenerator
            codeGen = codeProvider.CreateGenerator
            fileExtension = Me.codeProvider.FileExtension
            If (fileExtension Is Nothing) Then
                fileExtension = String.Empty
            ElseIf ((fileExtension.Length > 0) AndAlso (fileExtension.Chars(0) <> "."c)) Then
                fileExtension = ("." & fileExtension)
            End If
        Else
            fileExtension = ".src"
            codeGen = Nothing
        End If
    End Sub

    Private Function CreateDiscoveryClient() As DiscoveryClientProtocol
        Dim protocol As New DiscoveryClientProtocol
        protocol.AllowAutoRedirect = True
        'If ((Not Me.WsdlProperties.UserName Is Nothing) AndAlso (Me.WsdlProperties.UserName.Length <> 0)) Then
        '    protocol.Credentials = New NetworkCredential(Me.WsdlProperties.UserName, Me.WsdlProperties.Password, Me.WsdlProperties.Domain)
        'Else
        '    protocol.Credentials = CredentialCache.DefaultCredentials
        'End If
        'If ((Not Me.WsdlProperties.ProxyServer Is Nothing) AndAlso (Me.WsdlProperties.ProxyServer.Length <> 0)) Then
        '    Dim proxy As IWebProxy = Nothing
        '    proxy = New WebProxy(Me.WsdlProperties.ProxyServer)
        '    proxy.Credentials = New NetworkCredential(Me.WsdlProperties.ProxyUserName, Me.WsdlProperties.ProxyPassword, Me.WsdlProperties.ProxyDomain)
        '    protocol.Proxy = proxy
        'End If
        Return protocol
    End Function

    Private Shared Function CreateFakeSoapEncodingSchema(ByVal ns As String, ByVal name As String) As XmlSchema
        Dim schema As New XmlSchema
        schema.TargetNamespace = ns
        Dim item As New XmlSchemaGroup
        item.Name = "Array"
        Dim sequence As New XmlSchemaSequence
        Dim any As New XmlSchemaAny
        any.MinOccurs = 0
        any.MaxOccurs = 79228162514264337
        sequence.Items.Add(any)
        any.Namespace = "##any"
        any.ProcessContents = XmlSchemaContentProcessing.Lax
        item.Particle = sequence
        schema.Items.Add(item)
        Dim type As New XmlSchemaComplexType
        type.Name = name
        Dim ref2 As New XmlSchemaGroupRef
        ref2.RefName = New XmlQualifiedName("Array", ns)
        type.Particle = ref2
        Dim attribute As New XmlSchemaAttribute
        attribute.RefName = New XmlQualifiedName("arrayType", ns)
        type.Attributes.Add(attribute)
        schema.Items.Add(type)
        attribute = New XmlSchemaAttribute
        attribute.Use = XmlSchemaUse.None
        attribute.Name = "arrayType"
        schema.Items.Add(attribute)
        Wsdl.AddSimpleType(schema, "base64", "base64Binary")
        Wsdl.AddElementAndType(schema, "anyURI", ns)
        Wsdl.AddElementAndType(schema, "base64Binary", ns)
        Wsdl.AddElementAndType(schema, "boolean", ns)
        Wsdl.AddElementAndType(schema, "byte", ns)
        Wsdl.AddElementAndType(schema, "date", ns)
        Wsdl.AddElementAndType(schema, "dateTime", ns)
        Wsdl.AddElementAndType(schema, "decimal", ns)
        Wsdl.AddElementAndType(schema, "double", ns)
        Wsdl.AddElementAndType(schema, "duration", ns)
        Wsdl.AddElementAndType(schema, "ENTITIES", ns)
        Wsdl.AddElementAndType(schema, "ENTITY", ns)
        Wsdl.AddElementAndType(schema, "float", ns)
        Wsdl.AddElementAndType(schema, "gDay", ns)
        Wsdl.AddElementAndType(schema, "gMonth", ns)
        Wsdl.AddElementAndType(schema, "gMonthDay", ns)
        Wsdl.AddElementAndType(schema, "gYear", ns)
        Wsdl.AddElementAndType(schema, "gYearMonth", ns)
        Wsdl.AddElementAndType(schema, "hexBinary", ns)
        Wsdl.AddElementAndType(schema, "ID", ns)
        Wsdl.AddElementAndType(schema, "IDREF", ns)
        Wsdl.AddElementAndType(schema, "IDREFS", ns)
        Wsdl.AddElementAndType(schema, "int", ns)
        Wsdl.AddElementAndType(schema, "integer", ns)
        Wsdl.AddElementAndType(schema, "language", ns)
        Wsdl.AddElementAndType(schema, "long", ns)
        Wsdl.AddElementAndType(schema, "Name", ns)
        Wsdl.AddElementAndType(schema, "NCName", ns)
        Wsdl.AddElementAndType(schema, "negativeInteger", ns)
        Wsdl.AddElementAndType(schema, "NMTOKEN", ns)
        Wsdl.AddElementAndType(schema, "NMTOKENS", ns)
        Wsdl.AddElementAndType(schema, "nonNegativeInteger", ns)
        Wsdl.AddElementAndType(schema, "nonPositiveInteger", ns)
        Wsdl.AddElementAndType(schema, "normalizedString", ns)
        Wsdl.AddElementAndType(schema, "positiveInteger", ns)
        Wsdl.AddElementAndType(schema, "QName", ns)
        Wsdl.AddElementAndType(schema, "short", ns)
        Wsdl.AddElementAndType(schema, "string", ns)
        Wsdl.AddElementAndType(schema, "time", ns)
        Wsdl.AddElementAndType(schema, "token", ns)
        Wsdl.AddElementAndType(schema, "unsignedByte", ns)
        Wsdl.AddElementAndType(schema, "unsignedInt", ns)
        Wsdl.AddElementAndType(schema, "unsignedLong", ns)
        Wsdl.AddElementAndType(schema, "unsignedShort", ns)
        Return schema
    End Function

    Private Shared Function CreateFakeWsdlSchema(ByVal ns As String) As XmlSchema
        Dim schema As New XmlSchema
        schema.TargetNamespace = ns
        Dim item As New XmlSchemaAttribute
        item.Use = XmlSchemaUse.None
        item.Name = "arrayType"
        item.SchemaTypeName = New XmlQualifiedName("QName", "http://www.w3.org/2001/XMLSchema")
        schema.Items.Add(item)
        Return schema
    End Function

    Private Shared Function CreateFakeXsdSchema(ByVal ns As String, ByVal name As String) As XmlSchema
        Dim schema As New XmlSchema
        schema.TargetNamespace = ns
        Dim item As New XmlSchemaElement
        item.Name = name
        Dim type As New XmlSchemaComplexType
        item.SchemaType = type
        schema.Items.Add(item)
        Return schema
    End Function

    Private Shared Function FileExists(ByVal path As String) As Boolean
        Dim flag As Boolean
        If ((path Is Nothing) OrElse (path.Length = 0)) Then
            Return False
        End If
        Try
            flag = ((path.LastIndexOf("?"c) = -1) AndAlso File.Exists(path))
        Catch obj1 As Exception
        End Try
        Return flag
    End Function

    Public Sub Generate()
        Me.CheckPoint(MessageType.Begin, "Initializing")
        Dim descriptions As New ServiceDescriptionCollection
        Dim schemas As New XmlSchemas
        Dim urls As New StringCollection
        Dim localPaths As New StringCollection
        Me.GetPaths(localPaths, urls)
        descriptions.Clear()
        schemas.Clear()
        If ((Not localPaths Is Nothing) AndAlso (localPaths.Count > 0)) Then
            Dim path As String = localPaths.Item(0)
            Dim extension As String = GetExtension(path)
            If ((String.Compare(extension, ".exe", True) = 0) OrElse (String.Compare(extension, ".dll", True) = 0)) Then
                Me.CheckPoint(MessageType.Begin, "Loading Assembly")
                Me.proxyAssembly1 = Assembly.LoadFrom(path)
                If (Not Me.ProxyAssembly Is Nothing) Then
                    Me.CheckPoint(MessageType.Success, "Loaded Assembly")
                Else
                    Me.CheckPoint(MessageType.Failure, "Failed to load Assembly")
                End If
                Return
            End If
        End If
        Me.CheckPoint(MessageType.Begin, "Generating WSDL")
        Try
            Dim client As DiscoveryClientProtocol = Me.CreateDiscoveryClient
            Me.ProcessLocalPaths(client, localPaths, schemas, descriptions)
            Me.ProcessRemoteUrls(client, urls, schemas, descriptions)
        Catch exception As Exception
            Me.CheckPoint(MessageType.Failure, exception.ToString)
            Throw exception
            Return
        End Try
        Try
            Dim generator As ICodeGenerator
            Dim str3 As String
            Me.CheckPoint(MessageType.Begin, "Generating Proxy")
            Me.CreateCodeGenerator(generator, str3)
            Dim userSchemas As New XmlSchemas
            userSchemas.Add(schemas)
            Dim description As ServiceDescription
            For Each description In descriptions
                userSchemas.Add(description.Types.Schemas)
            Next
            Dim includeSchemas As New Hashtable
            Dim schema As XmlSchema
            For Each schema In userSchemas
                Wsdl.CollectIncludes(schema, includeSchemas)
            Next
            Me.Compile(userSchemas)
            Me.GenerateCode(descriptions, schemas, "http://tempuri.org", generator, str3)
            Me.CheckPoint(MessageType.Begin, "Compiling Proxy")
            Me.GenerateAssembly()
            Me.CheckPoint(MessageType.Success, "Generated Assembly")
            Me.ServiceDescriptions = descriptions
        Catch exception2 As Exception
            Me.CheckPoint(MessageType.Failure, exception2.ToString)
            Throw exception2
        End Try
    End Sub


    Private Sub GenerateAssembly()
        Dim compiler As ICodeCompiler = Me.codeProvider.CreateCompiler

        Dim location As String = ""
        If ((Not Me.WsdlProperties.ProxyBaseType Is Nothing) AndAlso (Me.WsdlProperties.ProxyBaseType.Length > 0)) Then
            location = Type.GetType(Me.WsdlProperties.ProxyBaseType, True).Assembly.Location
        End If
        Dim assemblyNames As String() = New String() {"System.Xml.dll", "System.dll", "System.Web.Services.dll", "System.Data.dll", "C:\Program Files\Microsoft WSE\v2.0\Microsoft.Web.Services2.dll", Assembly.GetExecutingAssembly.Location, location}
        Dim options As New CompilerParameters(assemblyNames)
        options.WarningLevel = 0
        options.GenerateInMemory = False
        Dim results As CompilerResults = compiler.CompileAssemblyFromSource(options, Me.ProxyCode)
        If results.Errors.HasErrors Then
            Dim error1 As CompilerError
            For Each error1 In results.Errors
                Me.CheckPoint(MessageType.Error, error1.ToString)
            Next
            Throw New Exception("CompilationErrors")
        End If
        Me.proxyAssembly1 = results.CompiledAssembly
    End Sub

    Private Sub GenerateCode(ByVal sources As ServiceDescriptionCollection, ByVal schemas As XmlSchemas, ByVal uriToWSDL As String, ByVal codeGen As ICodeGenerator, ByVal fileExtension As String)
        Me.proxyCode1 = " <ERROR> "
        Dim w As StringWriter = Nothing
        Me.compileUnit = New CodeCompileUnit
        Dim importer As New ServiceDescriptionImporter
        importer.Schemas.Add(schemas)
        Dim description As ServiceDescription
        For Each description In sources
            importer.AddServiceDescription(description, "", "")
        Next
        importer.Style = ServiceDescriptionImportStyle.Client
        Dim protocol As Protocol = Me.WsdlProperties.Protocol
        importer.ProtocolName = Me.WsdlProperties.Protocol.ToString
        Dim namespace2 As New CodeNamespace(Me.ProxyNamespace)
        Me.compileUnit.Namespaces.Add(namespace2)
        Dim warnings As ServiceDescriptionImportWarnings = importer.Import(namespace2, Me.compileUnit)
        Try
            Try
                w = New StringWriter
            Catch obj1 As Exception
                Throw obj1
            End Try
            Dim stream As MemoryStream = Nothing
            If (schemas.Count > 0) Then
                Me.compileUnit.ReferencedAssemblies.Add("System.Data.dll")
                Dim schema As XmlSchema
                For Each schema In schemas
                    Dim targetNamespace As String = Nothing
                    Try
                        targetNamespace = schema.TargetNamespace
                        If XmlSchemas.IsDataSet(schema) Then
                            If (stream Is Nothing) Then
                                stream = New MemoryStream
                            End If
                            stream.Position = 0
                            stream.SetLength(0)
                            schema.Write(stream)
                            stream.Position = 0
                            Dim set1 As New DataSet
                            set1.ReadXmlSchema(stream)
                            System.Data.Design.TypedDataSetGenerator.Generate(set1, namespace2, codeGen)
                        End If
                        Continue For
                    Catch obj2 As Exception
                        Throw obj2
                    End Try
                Next
            End If
            Try
                Wsdl.GenerateVersionComment(Me.compileUnit.Namespaces.Item(0))
                Me.ChangeBaseType(Me.compileUnit)
                codeGen.GenerateCodeFromCompileUnit(Me.compileUnit, w, Nothing)
            Catch exception As Exception
                If (Not w Is Nothing) Then
                    w.Write("Exception in generating code")
                    w.Write(exception.Message)
                End If
                Throw New InvalidOperationException("Error generating ", exception)
            End Try
        Finally
            Me.proxyCode1 = w.ToString.Replace("System.Web.Services.Protocols.SoapHttpClientProtocol", "Microsoft.Web.Services2.WebServicesClientProtocol")

            If (Not w Is Nothing) Then
                w.Close()
            End If
        End Try
    End Sub

    Private Shared Sub GenerateVersionComment(ByVal codeNamespace As CodeNamespace)
        codeNamespace.Comments.Add(New CodeCommentStatement(""))
        Dim name As AssemblyName = Assembly.GetExecutingAssembly.GetName
        Dim version As Version = Environment.Version
        codeNamespace.Comments.Add(New CodeCommentStatement(("Assembly " & name.Name & " Version = " & version.ToString)))
        codeNamespace.Comments.Add(New CodeCommentStatement(""))
    End Sub

    Public Function GetCodeGenerator() As ICodeGenerator
        Dim generator As ICodeGenerator
        Dim str As String
        Me.CreateCodeGenerator(generator, str)
        Return generator
    End Function

    Private Sub GetPaths(ByVal localPaths As StringCollection, ByVal urls As StringCollection)
        Dim str As String
        For Each str In Me.Paths
            If Wsdl.FileExists(str) Then
                If Not Path.HasExtension(str) Then
                    Throw New InvalidOperationException((str & " has no extensions"))
                End If
                localPaths.Add(str)
            Else
                Dim uri As Uri = Nothing
                Try
                    uri = New Uri(str)
                Catch exception1 As Exception
                    uri = Nothing
                End Try
                If (uri Is Nothing) Then
                    Throw New InvalidOperationException((str & " is invalid URI"))
                End If
                urls.Add(uri.AbsoluteUri)
            End If
        Next
    End Sub

    Private Sub ProcessLocalPaths(ByVal client As DiscoveryClientProtocol, ByVal localPaths As StringCollection, ByVal schemas As XmlSchemas, ByVal descriptions As ServiceDescriptionCollection)
        Dim str As String
        For Each str In localPaths
            Dim extension As String = Path.GetExtension(str)
            If (String.Compare(extension, ".discomap", True) = 0) Then
                client.ReadAll(str)
            Else
                Dim document As Object = Nothing
                If (String.Compare(extension, ".wsdl", True) = 0) Then
                    document = Me.ReadLocalDocument(False, str)
                Else
                    If (String.Compare(extension, ".xsd", True) <> 0) Then
                        Throw New InvalidOperationException(("Unknown file type " & str))
                    End If
                    document = Me.ReadLocalDocument(True, str)
                End If
                If (Not document Is Nothing) Then
                    Me.AddDocument(str, document, schemas, descriptions)
                End If
            End If
        Next
    End Sub

    Private Sub ProcessRemoteUrls(ByVal client As DiscoveryClientProtocol, ByVal urls As StringCollection, ByVal schemas As XmlSchemas, ByVal descriptions As ServiceDescriptionCollection)
        Dim str As String
        For Each str In urls
            Try
                'Dim tempbyte() As Byte
                Dim str1 As String = ""
                If Not str.ToUpper.Contains("?WSDL") Then
                    str1 = str & "?wsdl"
                Else
                    str1 = str
                End If
                Dim memstream As MemoryStream = client.Download(str1)
                Dim objreader As New StreamReader(memstream)
                Me.WSDLDoc = objreader.ReadToEnd

                Dim document As DiscoveryDocument = client.DiscoverAny(str)
                client.ResolveAll()
                Continue For
            Catch exception As Exception
                Throw New InvalidOperationException(("General Error " & str), exception)
            End Try
        Next
        Dim entry As DictionaryEntry
        For Each entry In client.Documents
            Me.AddDocument(CStr(entry.Key), entry.Value, schemas, descriptions)
        Next
    End Sub

    Private Function ReadLocalDocument(ByVal isSchema As Boolean, ByVal path As String) As Object
        Dim obj2 As Object = Nothing
        Dim input As StreamReader = Nothing
        Try
            input = New StreamReader(path)
            If isSchema Then
                Return XmlSchema.Read(New XmlTextReader(input), Nothing)
            End If
            obj2 = ServiceDescription.Read(input.BaseStream)
        Catch obj1 As Exception
            'Throw
        Finally
            If (Not input Is Nothing) Then
                input.Close()
            End If
        End Try
        Return obj2
    End Function

    Public Shared Function ReadSchema(ByVal filename As String) As XmlSchema
        Dim reader As New XmlTextReader(filename)
        If reader.IsStartElement("schema", "http://www.w3.org/2001/XMLSchema") Then
            Return XmlSchema.Read(reader, Nothing)
        End If
        Return Nothing
    End Function

    Public Sub Reset()
        Me.Paths.Clear()
        Me.codeProvider = Nothing
        Me.Wsdls.Clear()
        Me.Xsds.Clear()
        Me.compileUnit = Nothing
        Me.proxyAssembly1 = Nothing
        Me.proxyCode1 = Nothing
        Me.cancelled = False
    End Sub

    Private Sub ValidationCallbackWithErrorCode(ByVal sender As Object, ByVal args As ValidationEventArgs)
        Me.CheckPoint(MessageType.Warning, ("Schema parsing error " & args.Message))
    End Sub


    Private paths1 As New StringCollection
    Private proxyAssembly1 As Reflection.Assembly

    Private codeProvider1 As CodeDomProvider
    Private proxyCode1 As String
    Private proxyNamespace1 As String

    Private wsdls1 As StringCollection = New StringCollection
    Private xsds1 As StringCollection = New StringCollection


    Private strMessage As String

    Private WsdlException1 As Exception

    Private ServiceDescriptions1 As ServiceDescriptionCollection
    Private WsdlDoc1 As String

    Public Property WSDLDoc() As String
        Get
            Return WsdlDoc1
        End Get
        Set(ByVal value As String)
            WsdlDoc1 = value
        End Set
    End Property


    Public Property ServiceDescriptions() As ServiceDescriptionCollection
        Get
            Return ServiceDescriptions1
        End Get
        Set(ByVal value As ServiceDescriptionCollection)
            ServiceDescriptions1 = value
        End Set
    End Property


    Public Property WsdlException() As Exception
        Get
            Return WsdlException1
        End Get
        Set(ByVal value As Exception)
            WsdlException1 = value
        End Set
    End Property

    Public Property ErrorMemssage() As String
        Get
            Return strMessage
        End Get
        Set(ByVal value As String)
            strMessage = value
        End Set
    End Property

    ' Properties
    Public ReadOnly Property Paths() As StringCollection
        Get
            Return Me.paths1
        End Get
    End Property

    Public ReadOnly Property ProxyAssembly() As Assembly
        Get
            Return Me.proxyAssembly1
        End Get
    End Property

    Public ReadOnly Property ProxyCode() As String
        Get
            Return Me.proxyCode1
        End Get
    End Property

    Public ReadOnly Property ProxyCodeDom() As CodeCompileUnit
        Get
            Return Me.compileUnit
        End Get
    End Property

    Public ReadOnly Property ProxyFileExtension() As String
        Get
            Return Me.WsdlProperties.Language.ToString
        End Get
    End Property

    Public Property ProxyNamespace() As String
        Get
            Return Me.proxyNamespace1
        End Get
        Set(ByVal value As String)
            Me.proxyNamespace1 = value
        End Set
    End Property

    Public ReadOnly Property WsdlProperties() As WsdlProperties
        Get
            Return Configuration.MasterConfig.WsdlSettings
        End Get
    End Property

    Public ReadOnly Property Wsdls() As StringCollection
        Get
            Return Me.wsdls1
        End Get
    End Property

    Public ReadOnly Property Xsds() As StringCollection
        Get
            Return Me.xsds1
        End Get
    End Property


    ' Fields
    Private cancelled As Boolean = False
    Private codeProvider As CodeDomProvider = Nothing
    Private compileUnit As CodeCompileUnit
    Private Shared duplicateSchema As String = "Warning: Ignoring duplicate schema description with TargetNamespace='{0}' from '{1}'."
    Private Shared duplicateService As String = "Warning: Ignoring duplicate service description with TargetNamespace='{0}' from '{1}'."
    'Private paths As StringCollection = New StringCollection
    'Private proxyAssembly As Assembly
    'Private proxyCode As String = "<NOT YET>"
    'Private proxyNamespace As String = ""
    Private Shared schemaValidationFailure As String = "Schema could not be validated. Class generation may fail or may produce incorrect results"


    ' Nested Types
    Friend Class [Namespace]
        ' Fields
        Public Const SoapEncoding As String = "http://schemas.xmlsoap.org/soap/encoding/"
        Public Const Wsdl As String = "http://schemas.xmlsoap.org/wsdl/"
    End Class
End Class




<TypeConverter(GetType(ExpandableObjectConverter))> _
Public Class WsdlProperties
    ' Methods
    Public Function GetProxyBaseTypeList() As String()
        Return Configuration.MasterConfig.GetProxyBaseTypes
    End Function

    Public Overrides Function ToString() As String
        Return ""
    End Function


    ' Properties
    <RefreshProperties(RefreshProperties.All), XmlAttribute()> _
    Public Property CustomCodeDomProvider() As String
        Get
            Return IIf((Me.Language = Language.Custom), Me.customCodeDomProvider1, "")
        End Get
        Set(ByVal value As String)
            Me.customCodeDomProvider1 = value
            If ((Not value Is Nothing) AndAlso (value.Length > 0)) Then
                Me.language = Language.Custom
            End If
        End Set
    End Property

    <XmlAttribute()> _
    Public Property Domain() As String
        Get
            Return Me.domain1
        End Get
        Set(ByVal value As String)
            Me.domain1 = value
        End Set
    End Property

    <XmlAttribute(), RefreshProperties(RefreshProperties.All)> _
    Public Property Language() As Language
        Get
            Return Me.language1
        End Get
        Set(ByVal value As Language)
            Me.language1 = value
        End Set
    End Property

    <XmlAttribute()> _
    Public Property Password() As String
        Get
            Return Me.password1
        End Get
        Set(ByVal value As String)
            Me.password1 = value
        End Set
    End Property

    <XmlAttribute()> _
    Public Property Protocol() As Protocol
        Get
            Return Me.protocol1
        End Get
        Set(ByVal value As Protocol)
            Me.protocol1 = value
        End Set
    End Property

    <TypeConverter(GetType(ListStandardValues)), XmlAttribute()> _
    Public Property ProxyBaseType() As String
        Get
            Return Me.proxyBaseType1
        End Get
        Set(ByVal value As String)
            Me.proxyBaseType1 = value
        End Set
    End Property

    <XmlAttribute()> _
    Public Property ProxyDomain() As String
        Get
            Return Me.proxyDomain1
        End Get
        Set(ByVal value As String)
            Me.proxyDomain1 = value
        End Set
    End Property

    <XmlAttribute()> _
    Public Property ProxyPassword() As String
        Get
            Return Me.proxyPassword1
        End Get
        Set(ByVal value As String)
            Me.proxyPassword1 = value
        End Set
    End Property

    <XmlAttribute()> _
    Public Property ProxyServer() As String
        Get
            Return Me.proxy1
        End Get
        Set(ByVal value As String)
            Me.proxy1 = value
        End Set
    End Property

    <XmlAttribute()> _
    Public Property ProxyUserName() As String
        Get
            Return Me.proxyUserName1
        End Get
        Set(ByVal value As String)
            Me.proxyUserName1 = value
        End Set
    End Property

    <XmlAttribute()> _
    Public Property UserName() As String
        Get
            Return Me.userName1
        End Get
        Set(ByVal value As String)
            Me.userName1 = value
        End Set
    End Property


    ' Fields
    Private customCodeDomProvider1 As String
    Private domain1 As String
    Private language1 As Language
    Private password1 As String
    Private protocol1 As Protocol
    Private proxy1 As String
    Private proxyBaseType1 As String
    Private proxyDomain1 As String
    Private proxyPassword1 As String
    Private proxyUserName1 As String
    Private userName1 As String
End Class


Public Enum Protocol
    ' Fields
    HttpGet = 2
    HttpPost = 3
    SOAP = 0
    SOAP12 = 1
End Enum



<TypeConverter(GetType(ExpandableObjectConverter))> _
Public Class Configuration
    ' Methods
    Public Function Copy() As Configuration
        Dim stream As New MemoryStream
        Dim serializer As New XmlSerializer(GetType(Configuration))
        serializer.Serialize(DirectCast(stream, Stream), Configuration.masterConfig)
        stream.Position = 0
        Return TryCast(serializer.Deserialize(stream), Configuration)
    End Function

    Private Shared Function GetConfigFileName() As String
        Dim strpath As String = HttpContext.Current.Server.MapPath("")
        Return (strpath & "\bin\App.options")
    End Function

    Friend Function GetProxyBaseTypes() As String()
        Dim proxyProperties As CustomHandler() = Me.ProxyProperties
        Dim strArray As String() = New String(IIf((Not proxyProperties Is Nothing), (proxyProperties.Length + 1), 1) - 1) {}
        strArray(0) = ""
        Dim i As Integer
        For i = 1 To strArray.Length - 1
            strArray(i) = proxyProperties((i - 1)).TypeName
        Next i
        Return strArray
    End Function

    Public Shared Sub LoadMasterConfig()
        Try
            Dim stream As FileStream = File.OpenRead(Configuration.GetConfigFileName)
            Dim textReader As New StreamReader(stream)
            Dim serializer As New XmlSerializer(GetType(Configuration))
            Configuration.MasterConfig = TryCast(serializer.Deserialize(textReader), Configuration)
            stream.Flush()
            stream.Close()
        Catch obj1 As Exception
        End Try
        If (Configuration.masterConfig Is Nothing) Then
            Configuration.masterConfig = New Configuration
        End If
        If (Configuration.masterConfig.DataEditors Is Nothing) Then
            Configuration.masterConfig.DataEditors = New CustomHandler(0 - 1) {}
        End If
        If (Configuration.masterConfig.TypeConverters Is Nothing) Then
            Configuration.masterConfig.TypeConverters = New CustomHandler(0 - 1) {}
        End If
        If (Configuration.masterConfig.WsdlSettings Is Nothing) Then
            Configuration.masterConfig.WsdlSettings = New WsdlProperties
        End If
        If (Configuration.masterConfig.UiSettings Is Nothing) Then
            Configuration.masterConfig.UiSettings = New UiProperties
        End If
    End Sub

    Public Shared Sub SaveMasterConfig()
        Dim stream As FileStream = File.OpenWrite(Configuration.GetConfigFileName & ".write")
        Dim writer As New StreamWriter(stream)
        'New XmlSerializer(GetType(Configuration)).Serialize(DirectCast(writer, TextWriter), Configuration.masterConfig)
        stream.SetLength(stream.Position)
        stream.Flush()
        stream.Close()
    End Sub


    ' Properties
    <Browsable(False)> _
    Public Property DataEditors() As CustomHandler()
        Get
            Return Me.dataEditors1
        End Get
        Set(ByVal value As CustomHandler())
            Me.dataEditors1 = value
        End Set
    End Property

    <Browsable(False)> _
    Public Property InvokeSettings() As InvokeProperties
        Get
            Return Me.invokeSettings1
        End Get
        Set(ByVal value As InvokeProperties)
            Me.invokeSettings1 = value
        End Set
    End Property

    Friend Shared Property MasterConfig() As Configuration
        Get
            If (Configuration.masterConfig1 Is Nothing) Then
                Configuration.LoadMasterConfig()
            End If
            Return Configuration.masterConfig1
        End Get
        Set(ByVal value As Configuration)
            Configuration.masterConfig1 = value
            Configuration.SaveMasterConfig()
        End Set
    End Property

    <Browsable(False)> _
    Public Property ProxyProperties() As CustomHandler()
        Get
            Return Me.proxyProperties1
        End Get
        Set(ByVal value As CustomHandler())
            Me.proxyProperties1 = value
        End Set
    End Property

    <Browsable(False)> _
    Public Property TypeConverters() As CustomHandler()
        Get
            Return Me.typeConverters1
        End Get
        Set(ByVal value As CustomHandler())
            Me.typeConverters1 = value
        End Set
    End Property

    Public Property UiSettings() As UiProperties
        Get
            Return Me.uiSettings1
        End Get
        Set(ByVal value As UiProperties)
            Me.uiSettings1 = value
        End Set
    End Property

    Public Property WsdlSettings() As WsdlProperties
        Get
            Return Me.wsdlSettings1
        End Get
        Set(ByVal value As WsdlProperties)
            Me.wsdlSettings1 = value
        End Set
    End Property


    ' Fields
    Private dataEditors1 As CustomHandler()
    Private invokeSettings1 As InvokeProperties = New InvokeProperties
    Private Shared masterConfig1 As Configuration = Nothing
    Private proxyProperties1 As CustomHandler()
    Private typeConverters1 As CustomHandler()
    Private uiSettings1 As UiProperties
    Private wsdlSettings1 As WsdlProperties
End Class



<ComponentModel.TypeConverter(GetType(ComponentModel.ExpandableObjectConverter))> _
Public Class CustomHandler
    ' Methods
    Public Overrides Function ToString() As String
        Return (Me.Handler & "{" & Me.TypeName & "}")
    End Function


    ' Properties
    <XmlAttribute()> _
    Public Property Handler() As String
        Get
            Return Me.handler1
        End Get
        Set(ByVal value As String)
            Me.handler1 = value
        End Set
    End Property

    <XmlAttribute()> _
    Public Property TypeName() As String
        Get
            Return Me.typeName1
        End Get
        Set(ByVal value As String)
            Me.typeName1 = value
        End Set
    End Property


    ' Fields
    Private handler1 As String
    Private typeName1 As String
End Class

<ComponentModel.TypeConverter(GetType(ComponentModel.ExpandableObjectConverter))> _
Public Class InvokeProperties
    ' Methods
    Public Sub AddUri(ByVal uri As String)
        Me.uris.Remove(uri)
        Me.uris.Insert(0, uri)
        Configuration.SaveMasterConfig()
    End Sub

    Public Overrides Function ToString() As String
        Return ""
    End Function


    ' Properties
    <XmlArrayItem("Uri", GetType(String)), ComponentModel.Browsable(False)> _
    Public Property RecentlyUsedUris() As String()
        Get
            Return TryCast(Me.uris.ToArray(GetType(String)), String())
        End Get
        Set(ByVal value As String())
            Me.uris.Clear()
            If (Not value Is Nothing) Then
                Me.uris.AddRange(value)
            End If
        End Set
    End Property


    ' Fields
    Private uris As ArrayList = New ArrayList
End Class



<TypeConverter(GetType(ExpandableObjectConverter))> _
Public Class UiProperties
    ' Methods
    Public Overrides Function ToString() As String
        Return ""
    End Function


    ' Properties
    <XmlIgnore(), TypeConverter(GetType(FontConverter))> _
    Public Property MessageFont() As Font
        Get
            If (Me.messageFont1 Is Nothing) Then
                Me.messageFont1 = New Font("Lucida Sans Unicode", 9.25!, 0, 3, 0)
            End If
            Return Me.messageFont1
        End Get
        Set(ByVal value As Font)
            Me.messageFont1 = value
        End Set
    End Property

    <Browsable(False), XmlElement("MessageFont")> _
    Public Property MessageFontX() As String
        Get
            Return CStr(UiProperties.fontConverter1.ConvertTo(Nothing, Nothing, Me.MessageFont, GetType(String)))
        End Get
        Set(ByVal value As String)
            Me.MessageFont = DirectCast(UiProperties.fontConverter1.ConvertFrom(Nothing, Nothing, value), Font)
        End Set
    End Property

    <TypeConverter(GetType(FontConverter)), XmlIgnore()> _
    Public Property ReqRespFont() As Font
        Get
            If (Me.reqRespFont1 Is Nothing) Then
                Me.reqRespFont1 = New Font("Lucida Sans Unicode", 9.25!, 0, 3, 0)
            End If
            Return Me.reqRespFont1
        End Get
        Set(ByVal value As Font)
            Me.reqRespFont1 = value
        End Set
    End Property

    <ComponentModel.Browsable(False), XmlElement("ReqRespFont")> _
    Public Property ReqRespFontX() As String
        Get
            Return CStr(UiProperties.fontConverter1.ConvertTo(Nothing, Nothing, Me.reqRespFont, GetType(String)))
        End Get
        Set(ByVal value As String)
            Me.reqRespFont = DirectCast(UiProperties.fontConverter1.ConvertFrom(Nothing, Nothing, value), Drawing.Font)
        End Set
    End Property

    <XmlIgnore(), ComponentModel.TypeConverter(GetType(Drawing.FontConverter))> _
    Public Property WsdlFont() As Drawing.Font
        Get
            If (Me.wsdlFont1 Is Nothing) Then
                Me.wsdlFont1 = New Drawing.Font("Lucida Sans Unicode", 8.25!, 0, 3, 0)
            End If
            Return Me.wsdlFont1
        End Get
        Set(ByVal value As Drawing.Font)
            Me.wsdlFont1 = value
        End Set
    End Property

    <XmlElement("WsdlFont"), ComponentModel.Browsable(False)> _
    Public Property WsdlFontX() As String
        Get
            Return CStr(UiProperties.fontConverter1.ConvertTo(Nothing, Nothing, Me.wsdlFont, GetType(String)))
        End Get
        Set(ByVal value As String)
            Me.wsdlFont = DirectCast(UiProperties.fontConverter1.ConvertFrom(Nothing, Nothing, value), Drawing.Font)
        End Set
    End Property


    ' Fields
    Private Shared fontConverter1 As Drawing.FontConverter = New Drawing.FontConverter
    Private messageFont1 As Drawing.Font
    Private reqRespFont1 As Drawing.Font
    Private wsdlFont1 As Drawing.Font
End Class




Friend Class ListStandardValues
    Inherits TypeConverter
    ' Methods
    Public Overrides Function CanConvertFrom(ByVal context As ITypeDescriptorContext, ByVal sourceType As Type) As Boolean
        Return ((sourceType Is GetType(String)) OrElse MyBase.CanConvertFrom(context, sourceType))
    End Function

    Public Overrides Function ConvertFrom(ByVal context As ITypeDescriptorContext, ByVal culture As Globalization.CultureInfo, ByVal value As Object) As Object
        If TypeOf value Is String Then
            Dim possibleValues As Array = Me.GetPossibleValues(context)
            If (Not possibleValues Is Nothing) Then
                Dim obj2 As Object
                For Each obj2 In possibleValues
                    If (obj2.ToString = value.ToString) Then
                        Return obj2
                    End If
                Next
            End If
        End If
        Return MyBase.ConvertFrom(context, culture, value)
    End Function

    Protected Overridable Function GetPossibleValues(ByVal context As ITypeDescriptorContext) As Array
        Dim method As MethodInfo = context.Instance.GetType.GetMethod(("Get" & context.PropertyDescriptor.Name & "List"))
        If (method Is Nothing) Then
            Return Nothing
        End If
        Return TryCast(method.Invoke(context.Instance, Nothing), Array)
    End Function

    Public Overrides Function GetStandardValues(ByVal context As ITypeDescriptorContext) As StandardValuesCollection
        Dim possibleValues As Array = Me.GetPossibleValues(context)
        Return New StandardValuesCollection(IIf((Not possibleValues Is Nothing), DirectCast(possibleValues, ICollection), DirectCast(New Object(0 - 1) {}, ICollection)))
    End Function

    Public Overrides Function GetStandardValuesSupported(ByVal context As ITypeDescriptorContext) As Boolean
        Return True
    End Function

End Class

Public Enum MessageType
    ' Fields
    Begin = 0
    [Error] = 4
    Failure = 2
    Success = 1
    Warning = 3
End Enum


Public Enum Language
    ' Fields
    CS = 0
    Custom = 2
    VB = 1
End Enum


